/*
 * @Description: 请求全局拦截
 * @Author: 黄智超
 * @Date: 2019-09-12 11:44:54
 * @LastEditTime : 2019-12-18 19:09:09
 * @LastEditors  : Please set LastEditors
 */
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import store from '@/store';
import { getToken } from '@/utils/auth';
import { GetRequest } from './index';
import JSON5 from 'json5';
import { removeToken } from './auth';
import Cookies from 'js-cookie';
export const apiUrl = process.env.BASE_API;
// create an axios instance
const service = axios.create({
  baseURL: apiUrl, // api 的 base_url
  timeout: 300000, // request timeout 超时时间为5分钟
  withCredentials: true,
  transformResponse: [
    function transformResponse(data) {
      /*eslint no-param-reassign:0*/
      if (typeof data === 'string') {
        try {
          data = JSON5.parse(data);
        } catch (e) {
          /* Ignore */
          console.log(e, '出错啦');
        }
      }
      return data;
    },
  ],
});

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    //判斷token是否由URL傳入
    let data = GetRequest(window.location.href);
    if (data.AuthToken) {
      Cookies.set('authToken', data.AuthToken);
      config.headers['AuthToken'] = data.AuthToken;
    }

    if (store.getters.token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['AuthToken'] = getToken();
    }

    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  },
);

// response interceptor
// respone拦截器
let msgbox = null;
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== 1000) {
      if (res.httpCode === 401) {
        MessageBox.confirm('您已被登出，即将重新登录！', '通知', {
          type: 'warning',
          closeOnClickModal: false,
          showCancelButton: false,
          showConfirmButton: false,
          showClose: false,
          center: true,
          roundButton: true,
        });
        window.setTimeout(function() {
          store.dispatch('FedLogOut').then(() => {
            //判斷token是否由URL傳入
            let data = GetRequest(window.location.href);
            console.log(data.AuthToken);
            if (data.AuthToken) {
              //這個狀態獲取不到$router 先用原生的處理
              window.location.href =
                window.location.protocol +
                '//' +
                window.location.host +
                '/#/login';
            } else {
              location.reload(); // 为了重新实例化vue-router对象 避免bug
              let loginUrl = window.localStorage.getItem('customLogin');
              if (loginUrl) {
                this.$router.push({ path: loginUrl });
              } else {
                this.$router.push({ path: '/login' });
              }
            }
          });
        }, 2000);
      } else if (!res.success) {
        //Message.error(res.msg);
        Message({
          message: res.msg,
          type: 'error',
          duration: 3 * 1000,
        });
        return Promise.reject(res); //实际上是异常的请求 后端抛出的错误消息
      } else if (res.code === 2000) {
        return response;
      } else {
        return response;
      }
    } else {
      return response;
    }
  },
  error => {
    if (error.response == undefined) {
      Message({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000,
      });
      return false;
    }
    let message = error.response.statusText;
    if (error.response.data) message = error.response.data.msg;
    if (!message) message = '服务器正在维护或网络不可用，请稍后再试~';
    if (!msgbox) {
      msgbox = Message({
        message: message,
        type: 'error',
        duration: 5 * 1000,
      });
    }

    return Promise.reject(error);
  },
);

export default service;
